<?php
require_once 'config.php';

try {
	$db = new PDO('pgsql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
	print "Error!: " . $e->getMessage();
	die();
}
$result = '';
if (isset($_GET['TOKEN'])) {
	$token = $_GET['TOKEN'];
	$sql = sprintf('SELECT "ID" FROM "BOOKS" WHERE "TOKEN" LIKE \'%s\'', $token);
	$stmt = $db->query($sql)->fetch();
	$result = $stmt;

	if (isset($stmt['ID'])) {
		$sql = 'SELECT "ID","NAME","AUTOR","PRICE","AMOUNT" FROM "BOOKS"';
		$stmt = $db->query($sql);
		$result = '{"books":[';
		while ($row = $stmt->fetch()) {
			$result .= sprintf('{"id":%d,"name":"%s","autor":"%s","price":"%s","amount":"%s"},',$row['ID'],$row['NAME'],$row['AUTOR'],$row['PRICE'],$row['AMOUNT']);
		}
		$result = rtrim($result, ",");
		$result .= ']}';
	}
	
	
}
echo $result;

?> 
